package com.tul.vapp.servicecenter.client;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeSet;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import com.tul.vapp.servicecenter.common.StatusEnum;

/**
 * 配置客户端
 * 
 * @author wwxiang
 * @author wujunlei
 * @since 2018/1/3.
 */
public class ConfigClient implements IConfigClient {

	private static final Logger LOGGER = LoggerFactory.getLogger(ConfigClient.class);

	private Repository repository;

	private ReportRepository reportRepository;

	/**
	 * 构造函数
	 * 
	 * @param appId appId
	 * @param startRemote 开启从ZK同步更新配置
	 */
	public ConfigClient(String appId, boolean startRemote) {
		this.repository = new Repository(appId, startRemote);
		if (startRemote) {
			// 只有开启远端配置，才可以进行服务状态报告
			this.reportRepository = new ReportRepository(appId);
		}
	}

	@Override
	public Set<String> getNamespaces() {
		return repository.listNamespace();
	}

	@Override
	public String getProperty(String namespace, String key) {
		String result = repository.getPropertyInZk(namespace, key);
		if (result == null) {
			result = repository.getPropertyInLocal(namespace, key);
		}
		return result;
	}

	@Override
	public Map<String, String> getProperties(String namespace) {
		return repository.getProperties(namespace);
	}

	@Override
	public String getProperty(String key) {
		String result = null;
		Set<String> ns = repository.listNamespace();
		for (String space : ns) {
			result = this.getProperty(space, key);
			if (result != null) {
				return result;
			}
		}
		return result;
	}

	public Set<String> scanProperty(String key) {
		Set<String> ns = repository.listNamespace();
		Set<String> vs = new TreeSet();
		for (String n : ns) {
			String value = this.getProperty(n, key);
			if (value == null) {
				continue;
			}
			vs.add(value);
		}
		return vs;
	}

	@Override
	public void report(StatusEnum statusEnum, String value) {
		if (reportRepository == null) {
			return;
		}
		reportRepository.publishStatus(statusEnum, value);
	}

	/**
	 * 给服务中心报告信息
	 *
	 * @param statusEnum 信息名称
	 * @param value 信息值
	 * @param appName 应用别名
	 */
	@Override
	public void report(StatusEnum statusEnum, String value, String appName) {
		if (reportRepository == null) {
			return;
		}
		reportRepository.publishStatus(statusEnum, value, appName);
	}

	@Override
	public void loadFile(List<String> nameSpaceList) {
		if (CollectionUtils.isEmpty(nameSpaceList)) {
			return;
		}
		for (String nameSpace : nameSpaceList) {
			Properties prop = new Properties();
			try {
				prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream(nameSpace));
			} catch (IOException e) {
				LOGGER.error("Error to loadFile. ", e);
			}
			repository.loadFile(nameSpace, prop);
		}

	}

	@Override
	public void subscribe() {
		repository.subscribe();
	}
}
